package com.example.netcapture.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.netcapture.dto.PacketInfoDto;
import com.example.netcapture.entity.PacketInfo;
import com.example.netcapture.service.PacketQueryService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/api/packets")
@RequiredArgsConstructor
public class PacketController {
    
    private final PacketQueryService packetQueryService;
    
    @GetMapping
    public ResponseEntity<Page<PacketInfoDto>> queryPackets(
            @RequestParam(required = false) String protocol,
            @RequestParam(required = false) String sourceIp,
            @RequestParam(required = false) String destinationIp,
            @RequestParam(required = false) Integer sourcePort,
            @RequestParam(required = false) Integer destinationPort,
            @RequestParam(required = false) String sessionId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(required = false) Boolean bidirectional,  // 添加双向过滤参数
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "20") int pageSize) {

        try {
            Page<PacketInfoDto> result = packetQueryService.queryPackets(
                    protocol, sourceIp, destinationIp, sourcePort, destinationPort, sessionId,
                    startTime, endTime, bidirectional, pageNo, pageSize
            );

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error querying packets", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    @GetMapping("/recent")
    public ResponseEntity<List<PacketInfo>> getRecentPackets(
            @RequestParam(defaultValue = "100") int limit) {
        try {
            List<PacketInfo> packets = packetQueryService.getRecentPackets(limit);
            return ResponseEntity.ok(packets);
        } catch (Exception e) {
            log.error("Error getting recent packets", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<PacketInfo> getPacketDetail(@PathVariable Long id) {
        try {
            PacketInfo packet = packetQueryService.getPacketDetail(id);
            if (packet != null) {
                return ResponseEntity.ok(packet);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("Error getting packet detail", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 删除所有数据包记录
     */
    @DeleteMapping
    public ResponseEntity<Void> deleteAllPackets() {
        try {
            int deletedCount = packetQueryService.deleteAllPackets();
            log.info("成功删除 {} 条数据包记录", deletedCount);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("删除数据包记录时发生错误", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 上传PCAP文件并导入数据包
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadPcapFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "clearExisting", defaultValue = "false") boolean clearExisting) {

        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "文件不能为空"
                ));
            }

            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null ||
                    (!originalFilename.toLowerCase().endsWith(".cap") &&
                            !originalFilename.toLowerCase().endsWith(".pcap") &&
                            !originalFilename.toLowerCase().endsWith(".pcapng"))) {
                return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "只支持 .cap、.pcap 和 .pcapng 格式的文件"
                ));
            }

            log.info("开始导入PCAP文件: {}, 大小: {} bytes, 清空现有数据: {}",
                    originalFilename, file.getSize(), clearExisting);

            // 调用服务层处理文件导入
            int importedCount = packetQueryService.importPcapFile(file, clearExisting);

            log.info("PCAP文件导入完成，成功导入 {} 个数据包", importedCount);

            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "importedCount", importedCount,
                    "message", "文件导入成功"
            ));

        } catch (Exception e) {
            log.error("PCAP文件导入失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "文件导入失败: " + e.getMessage()
            ));
        }
    }
}